package test.t1;

import java.util.concurrent.*;

public class ThreadComparison {

    private static void doWork() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 测量平台线程
    private static long measurePlatformThreads(int count) throws InterruptedException {
        // Runtime.getRuntime().availableProcessors()
        var executor = Executors.newFixedThreadPool(100);
        try {
            CountDownLatch latch = new CountDownLatch(count);
            long start = System.currentTimeMillis();

            for (int i = 0; i < count; i++) {
                executor.submit(() -> {
                    try {
                        Thread.sleep(2000);
                        doWork();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        latch.countDown();
                    }
                });
            }

            latch.await();
            return System.currentTimeMillis() - start;
        } finally {
            executor.shutdown();
        }
    }

    // 测量虚拟线程
    private static long measureVirtualThreads(int count) throws InterruptedException {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            CountDownLatch latch = new CountDownLatch(count);
            long start = System.currentTimeMillis();

            for (int i = 0; i < count; i++) {
                executor.submit(() -> {
                    try {
                        boolean isVirtual = Thread.currentThread().isVirtual();
//                        System.out.println("🚀 虚拟线程启动：" + isVirtual);
                        Thread.sleep(2000);
                        doWork();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        latch.countDown();
                    }
                });
            }

            latch.await();
            return System.currentTimeMillis() - start;
        }
    }

    public static void main(String[] args) throws Exception {
        int count = 10000;

        System.out.println("🚀 开始性能对比测试（" + count + " 个任务）");
        long platformTime = 0;

//        platformTime = measurePlatformThreads(count);
        long virtualTime = measureVirtualThreads(count);

        System.out.println("✅ 平台线程耗时: " + platformTime + " ms");
        System.out.println("✅ 虚拟线程耗时: " + virtualTime + " ms");

        System.out.println("\n📈 结果分析:");
        if (virtualTime < platformTime) {
            double speedup = (double) platformTime / virtualTime;
            System.out.println("🎉 虚拟线程更快！速度提升约 " + String.format("%.2f", speedup) + " 倍");
        } else {
            double slowdown = (double) virtualTime / platformTime;
            System.out.println("⚠️  平台线程更快（理论上不应发生），慢了 " + String.format("%.2f", slowdown) + " 倍");
        }
    }
}